package la.bbs558.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import la.bbs558.dao.UserConfigDao;
import la.bbs558.entity.User;
import la.bbs558.entity.UserConfig;
import la.bbs558.exception.MsgException;
import la.bbs558.service.UserConfigService;
import la.bbs558.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户配置表(UserConfig)表服务实现类
 *
 * @author weihanmin
 * @since 2023-12-17 16:12:29
 */
@Service("userConfigService")
public class UserConfigServiceImpl extends ServiceImpl<UserConfigDao, UserConfig> implements UserConfigService {
    @Resource
    private UserService userService;

    @Override
    public UserConfig initGetUserConfig(Long userId) {
        UserConfig userConfig = selectByUserId(userId);
        if (userConfig != null) {
            return userConfig;
        }
        Integer count = userService.lambdaQuery().eq(User::getId, userId).count();
        if (count == 0) {
            throw new MsgException("用户不存在");
        }
        userConfig = new UserConfig();
        userConfig.setUserId(userId);
        userConfig.insert();
        return selectByUserId(userId);
    }

    private UserConfig selectByUserId(Long userId) {
        return lambdaQuery().eq(UserConfig::getUserId, userId).one();
    }
}

